﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using IPC.Communication;
using IPC.Communication.BasicFramework;
using IPC.Communication.Core;
using IPC.Communication.Core.IMessage;
using IPC.Communication.Enthernet.Redis;
using IPC.Communication.LogNet;
using IPC.Communication.MQTT;
using IPC.Communication.WebSocket;

namespace IPC.Communication.Core.Net
{
    public abstract class NetworkBase
    {

	    protected Socket CoreSocket = null;

	    protected int fileCacheSize = 102400;

	    private int connectErrorCount = 0;

	    public ILogNet LogNet
	    {
		    get;
		    set;
	    }

	    public Guid Token
	    {
		    get;
		    set;
	    }

	    public NetworkBase()
	    {
		    Token = Guid.Empty;
	    }

	    protected OperateResult<int> Receive(Socket socket, byte[] buffer, int offset, int length, int timeOut = 60000, Action<long, long> reportProgress = null)
	    {
		    if (length == 0)
		    {
			    return OperateResult.CreateSuccessResult(0);
		    }
		    try
		    {
			    socket.ReceiveTimeout = timeOut;
			    if (length > 0)
			    {
				    NetSupport.ReceiveBytesFromSocket(socket, buffer, offset, length, reportProgress);
				    return OperateResult.CreateSuccessResult(length);
			    }
			    int num = socket.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None);
			    if (num == 0)
			    {
				    throw new RemoteCloseException();
			    }
			    return OperateResult.CreateSuccessResult(num);
		    }
		    catch (RemoteCloseException)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    if (connectErrorCount < 1000000000)
			    {
				    connectErrorCount++;
			    }
			    return new OperateResult<int>(-connectErrorCount, "Socket Exception -> " + StringResources.Language.RemoteClosedConnection);
		    }
		    catch (Exception ex2)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    if (connectErrorCount < 1000000000)
			    {
				    connectErrorCount++;
			    }
			    return new OperateResult<int>(-connectErrorCount, "Socket Exception -> " + ex2.Message);
		    }
	    }

	    protected OperateResult<byte[]> Receive(Socket socket, int length, int timeOut = 60000, Action<long, long> reportProgress = null)
	    {
		    if (length == 0)
		    {
			    return OperateResult.CreateSuccessResult(new byte[0]);
		    }
		    byte[] array = (length > 0) ? new byte[length] : new byte[2048];
		    OperateResult<int> operateResult = Receive(socket, array, 0, length, timeOut, reportProgress);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<byte[]>(operateResult);
		    }
		    return OperateResult.CreateSuccessResult((length > 0) ? array : array.SelectBegin(operateResult.Content));
	    }

	    protected OperateResult<byte[]> ReceiveCommandLineFromSocket(Socket socket, byte endCode, int timeout = 60000)
	    {
		    List<byte> list = new List<byte>(128);
		    try
		    {
			    DateTime now = DateTime.Now;
			    bool flag = false;
			    while ((DateTime.Now - now).TotalMilliseconds < (double)timeout)
			    {
				    if (socket.Poll(timeout, SelectMode.SelectRead))
				    {
					    OperateResult<byte[]> operateResult = Receive(socket, 1, timeout);
					    if (!operateResult.IsSuccess)
					    {
						    return operateResult;
					    }
					    list.AddRange(operateResult.Content);
					    if (operateResult.Content[0] == endCode)
					    {
						    flag = true;
						    break;
					    }
				    }
			    }
			    if (!flag)
			    {
				    return new OperateResult<byte[]>(StringResources.Language.ReceiveDataTimeout);
			    }
			    return OperateResult.CreateSuccessResult(list.ToArray());
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<byte[]>(ex.Message);
		    }
	    }

	    protected OperateResult<byte[]> ReceiveCommandLineFromSocket(Socket socket, byte endCode1, byte endCode2, int timeout = 60000)
	    {
		    List<byte> list = new List<byte>(128);
		    try
		    {
			    DateTime now = DateTime.Now;
			    bool flag = false;
			    while ((DateTime.Now - now).TotalMilliseconds < (double)timeout)
			    {
				    if (socket.Poll(timeout, SelectMode.SelectRead))
				    {
					    OperateResult<byte[]> operateResult = Receive(socket, 1, timeout);
					    if (!operateResult.IsSuccess)
					    {
						    return operateResult;
					    }
					    list.AddRange(operateResult.Content);
					    if (operateResult.Content[0] == endCode2 && list.Count > 1 && list[list.Count - 2] == endCode1)
					    {
						    flag = true;
						    break;
					    }
				    }
			    }
			    if (!flag)
			    {
				    return new OperateResult<byte[]>(StringResources.Language.ReceiveDataTimeout);
			    }
			    return OperateResult.CreateSuccessResult(list.ToArray());
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<byte[]>(ex.Message);
		    }
	    }

	    protected virtual OperateResult<byte[]> ReceiveByMessage(Socket socket, int timeOut, INetMessage netMessage, Action<long, long> reportProgress = null)
	    {
		    if (netMessage == null)
		    {
			    return Receive(socket, -1, timeOut);
		    }
		    OperateResult<byte[]> operateResult = Receive(socket, netMessage.ProtocolHeadBytesLength, timeOut);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult;
		    }
		    netMessage.HeadBytes = operateResult.Content;
		    int contentLengthByHeadBytes = netMessage.GetContentLengthByHeadBytes();
		    if (contentLengthByHeadBytes <= 0)
		    {
			    return OperateResult.CreateSuccessResult(operateResult.Content);
		    }
		    byte[] array = new byte[netMessage.ProtocolHeadBytesLength + contentLengthByHeadBytes];
		    operateResult.Content.CopyTo(array, 0);
		    OperateResult operateResult2 = Receive(socket, array, netMessage.ProtocolHeadBytesLength, contentLengthByHeadBytes, timeOut, reportProgress);
		    if (!operateResult2.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<byte[]>(operateResult2);
		    }
		    return OperateResult.CreateSuccessResult(array);
	    }

	    protected OperateResult Send(Socket socket, byte[] data)
	    {
		    if (data == null)
		    {
			    return OperateResult.CreateSuccessResult();
		    }
		    return Send(socket, data, 0, data.Length);
	    }

	    protected OperateResult Send(Socket socket, byte[] data, int offset, int size)
	    {
		    if (data == null)
		    {
			    return OperateResult.CreateSuccessResult();
		    }
		    try
		    {
			    int num = 0;
			    do
			    {
				    int num2 = socket.Send(data, offset, size - num, SocketFlags.None);
				    num += num2;
				    offset += num2;
			    }
			    while (num < size);
			    return OperateResult.CreateSuccessResult();
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    if (connectErrorCount < 1000000000)
			    {
				    connectErrorCount++;
			    }
			    return new OperateResult<byte[]>(-connectErrorCount, ex.Message);
		    }
	    }

	    protected OperateResult<Socket> CreateSocketAndConnect(string ipAddress, int port)
	    {
		    return CreateSocketAndConnect(new IPEndPoint(IPAddress.Parse(ipAddress), port), 10000);
	    }

	    protected OperateResult<Socket> CreateSocketAndConnect(string ipAddress, int port, int timeOut)
	    {
		    return CreateSocketAndConnect(new IPEndPoint(IPAddress.Parse(ipAddress), port), timeOut);
	    }

	    protected OperateResult<Socket> CreateSocketAndConnect(IPEndPoint endPoint, int timeOut, IPEndPoint local = null)
	    {
		    int num = 0;
		    while (true)
		    {
			    num++;
			    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			    HslTimeOut hslTimeOut = HslTimeOut.HandleTimeOutCheck(socket, timeOut);
			    try
			    {
				    if (local != null)
				    {
					    socket.Bind(local);
				    }
				    socket.Connect(endPoint);
				    connectErrorCount = 0;
				    hslTimeOut.IsSuccessful = true;
				    return OperateResult.CreateSuccessResult(socket);
			    }
			    catch (Exception ex)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    hslTimeOut.IsSuccessful = true;
				    if (connectErrorCount < 1000000000)
				    {
					    connectErrorCount++;
				    }
				    if (!(hslTimeOut.GetConsumeTime() < TimeSpan.FromMilliseconds(500.0)) || num >= 2)
				    {
					    if (hslTimeOut.IsTimeout)
					    {
						    return new OperateResult<Socket>(-connectErrorCount, string.Format(StringResources.Language.ConnectTimeout, endPoint, timeOut) + " ms");
					    }
					    return new OperateResult<Socket>(-connectErrorCount, String.Format("Socket Connect {0} Exception -> ", endPoint) + ex.Message);
				    }
				    Thread.Sleep(100);
			    }
		    }
	    }

	    protected OperateResult<int> ReadStream(Stream stream, byte[] buffer)
	    {
		    ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false);
		    FileStateObject fileStateObject = new FileStateObject
		    {
			    WaitDone = manualResetEvent,
			    Stream = stream,
			    DataLength = buffer.Length,
			    Buffer = buffer
		    };
		    try
		    {
			    stream.BeginRead(buffer, 0, fileStateObject.DataLength, ReadStreamCallBack, fileStateObject);
		    }
		    catch (Exception ex)
		    {
			    fileStateObject = null;
			    manualResetEvent.Close();
			    return new OperateResult<int>("stream.BeginRead Exception -> " + ex.Message);
		    }
		    manualResetEvent.WaitOne();
		    manualResetEvent.Close();
		    return fileStateObject.IsError ? new OperateResult<int>(fileStateObject.ErrerMsg) : OperateResult.CreateSuccessResult(fileStateObject.AlreadyDealLength);
	    }

	    private void ReadStreamCallBack(IAsyncResult ar)
	    {
		    FileStateObject fileStateObject = ar.AsyncState as FileStateObject;
		    if (fileStateObject != null)
		    {
			    try
			    {
				    fileStateObject.AlreadyDealLength += fileStateObject.Stream.EndRead(ar);
				    fileStateObject.WaitDone.Set();
			    }
			    catch (Exception ex)
			    {
				    fileStateObject.IsError = true;
				    fileStateObject.ErrerMsg = ex.Message;
				    fileStateObject.WaitDone.Set();
			    }
		    }
	    }

	    protected OperateResult WriteStream(Stream stream, byte[] buffer)
	    {
		    ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false);
		    FileStateObject fileStateObject = new FileStateObject
		    {
			    WaitDone = manualResetEvent,
			    Stream = stream
		    };
		    try
		    {
			    stream.BeginWrite(buffer, 0, buffer.Length, WriteStreamCallBack, fileStateObject);
		    }
		    catch (Exception ex)
		    {
			    fileStateObject = null;
			    manualResetEvent.Close();
			    return new OperateResult("stream.BeginWrite Exception -> " + ex.Message);
		    }
		    manualResetEvent.WaitOne();
		    manualResetEvent.Close();
		    if (fileStateObject.IsError)
		    {
			    return new OperateResult
			    {
				    Message = fileStateObject.ErrerMsg
			    };
		    }
		    return OperateResult.CreateSuccessResult();
	    }

	    private void WriteStreamCallBack(IAsyncResult ar)
	    {
		    FileStateObject fileStateObject = ar.AsyncState as FileStateObject;
		    if (fileStateObject != null)
		    {
			    try
			    {
				    fileStateObject.Stream.EndWrite(ar);
			    }
			    catch (Exception ex)
			    {
				    fileStateObject.IsError = true;
				    fileStateObject.ErrerMsg = ex.Message;
			    }
			    finally
			    {
				    fileStateObject.WaitDone.Set();
			    }
		    }
	    }

	    protected bool CheckRemoteToken(byte[] headBytes)
	    {
		    return SoftBasic.IsByteTokenEquel(headBytes, Token);
	    }

	    protected OperateResult SendBaseAndCheckReceive(Socket socket, int headCode, int customer, byte[] send)
	    {
		    send = HslProtocol.CommandBytes(headCode, customer, Token, send);
		    OperateResult operateResult = Send(socket, send);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult;
		    }
		    OperateResult<long> operateResult2 = ReceiveLong(socket);
		    if (!operateResult2.IsSuccess)
		    {
			    return operateResult2;
		    }
		    if (operateResult2.Content != send.Length)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult(StringResources.Language.CommandLengthCheckFailed);
		    }
		    return operateResult2;
	    }

	    protected OperateResult SendBytesAndCheckReceive(Socket socket, int customer, byte[] send)
	    {
		    return SendBaseAndCheckReceive(socket, 1002, customer, send);
	    }

	    protected OperateResult SendStringAndCheckReceive(Socket socket, int customer, string send)
	    {
		    byte[] send2 = string.IsNullOrEmpty(send) ? null : Encoding.Unicode.GetBytes(send);
		    return SendBaseAndCheckReceive(socket, 1001, customer, send2);
	    }

	    protected OperateResult SendStringAndCheckReceive(Socket socket, int customer, string[] sends)
	    {
		    return SendBaseAndCheckReceive(socket, 1005, customer, HslProtocol.PackStringArrayToByte(sends));
	    }

	    protected OperateResult SendAccountAndCheckReceive(Socket socket, int customer, string name, string pwd)
	    {
		    return SendBaseAndCheckReceive(socket, 5, customer, HslProtocol.PackStringArrayToByte(new string[2]
		    {
			    name,
			    pwd
		    }));
	    }

	    protected OperateResult<byte[], byte[]> ReceiveAndCheckBytes(Socket socket, int timeOut)
	    {
		    OperateResult<byte[]> operateResult = Receive(socket, 32, timeOut);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult.ConvertFailed<byte[], byte[]>();
		    }
		    if (!CheckRemoteToken(operateResult.Content))
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<byte[], byte[]>(StringResources.Language.TokenCheckFailed);
		    }
		    int num = BitConverter.ToInt32(operateResult.Content, 28);
		    OperateResult<byte[]> operateResult2 = Receive(socket, num, timeOut);
		    if (!operateResult2.IsSuccess)
		    {
			    return operateResult2.ConvertFailed<byte[], byte[]>();
		    }
		    OperateResult operateResult3 = SendLong(socket, 32 + num);
		    if (!operateResult3.IsSuccess)
		    {
			    return operateResult3.ConvertFailed<byte[], byte[]>();
		    }
		    byte[] content = operateResult.Content;
		    byte[] content2 = operateResult2.Content;
		    content2 = HslProtocol.CommandAnalysis(content, content2);
		    return OperateResult.CreateSuccessResult(content, content2);
	    }

	    protected OperateResult<int, string> ReceiveStringContentFromSocket(Socket socket, int timeOut = 30000)
	    {
		    OperateResult<byte[], byte[]> operateResult = ReceiveAndCheckBytes(socket, timeOut);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<int, string>(operateResult);
		    }
		    if (BitConverter.ToInt32(operateResult.Content1, 0) != 1001)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<int, string>(StringResources.Language.CommandHeadCodeCheckFailed);
		    }
		    if (operateResult.Content2 == null)
		    {
			    operateResult.Content2 = new byte[0];
		    }
		    return OperateResult.CreateSuccessResult(BitConverter.ToInt32(operateResult.Content1, 4), Encoding.Unicode.GetString(operateResult.Content2));
	    }

	    protected OperateResult<int, string[]> ReceiveStringArrayContentFromSocket(Socket socket, int timeOut = 30000)
	    {
		    OperateResult<byte[], byte[]> operateResult = ReceiveAndCheckBytes(socket, timeOut);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<int, string[]>(operateResult);
		    }
		    if (BitConverter.ToInt32(operateResult.Content1, 0) != 1005)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<int, string[]>(StringResources.Language.CommandHeadCodeCheckFailed);
		    }
		    if (operateResult.Content2 == null)
		    {
			    operateResult.Content2 = new byte[4];
		    }
		    return OperateResult.CreateSuccessResult(BitConverter.ToInt32(operateResult.Content1, 4), HslProtocol.UnPackStringArrayFromByte(operateResult.Content2));
	    }

	    protected OperateResult<int, byte[]> ReceiveBytesContentFromSocket(Socket socket, int timeout = 30000)
	    {
		    OperateResult<byte[], byte[]> operateResult = ReceiveAndCheckBytes(socket, timeout);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<int, byte[]>(operateResult);
		    }
		    if (BitConverter.ToInt32(operateResult.Content1, 0) != 1002)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<int, byte[]>(StringResources.Language.CommandHeadCodeCheckFailed);
		    }
		    return OperateResult.CreateSuccessResult(BitConverter.ToInt32(operateResult.Content1, 4), operateResult.Content2);
	    }

	    private OperateResult<long> ReceiveLong(Socket socket)
	    {
		    OperateResult<byte[]> operateResult = Receive(socket, 8, -1);
		    if (operateResult.IsSuccess)
		    {
			    return OperateResult.CreateSuccessResult(BitConverter.ToInt64(operateResult.Content, 0));
		    }
		    return OperateResult.CreateFailedResult<long>(operateResult);
	    }

	    private OperateResult SendLong(Socket socket, long value)
	    {
		    return Send(socket, BitConverter.GetBytes(value));
	    }

	    protected OperateResult SendStreamToSocket(Socket socket, Stream stream, long receive, Action<long, long> report, bool reportByPercent)
	    {
		    byte[] array = new byte[fileCacheSize];
		    long num = 0L;
		    long num2 = 0L;
		    stream.Position = 0L;
		    while (num < receive)
		    {
			    OperateResult<int> operateResult = ReadStream(stream, array);
			    if (!operateResult.IsSuccess)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    return operateResult;
			    }
			    num += operateResult.Content;
			    byte[] array2 = new byte[operateResult.Content];
			    Array.Copy(array, 0, array2, 0, array2.Length);
			    OperateResult operateResult2 = SendBytesAndCheckReceive(socket, operateResult.Content, array2);
			    if (!operateResult2.IsSuccess)
			    {
                    if (socket != null)
                    {
				        socket.Close();
                    }
				    return operateResult2;
			    }
			    if (reportByPercent)
			    {
				    long num3 = num * 100 / receive;
				    if (num2 != num3)
				    {
					    num2 = num3;
                        if (report != null)
                        {
                            report.Invoke(num, receive);
                        }
				    }
			    }
			    else
			    {
                    if (report != null)
                    {
                        report.Invoke(num, receive);
                    }
			    }
		    }
		    return OperateResult.CreateSuccessResult();
	    }

	    protected OperateResult WriteStreamFromSocket(Socket socket, Stream stream, long totalLength, Action<long, long> report, bool reportByPercent)
	    {
		    long num = 0L;
		    long num2 = 0L;
		    while (num < totalLength)
		    {
			    OperateResult<int, byte[]> operateResult = ReceiveBytesContentFromSocket(socket, 60000);
			    if (!operateResult.IsSuccess)
			    {
				    return operateResult;
			    }
			    num += operateResult.Content1;
			    OperateResult operateResult2 = WriteStream(stream, operateResult.Content2);
			    if (!operateResult2.IsSuccess)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    return operateResult2;
			    }
			    if (reportByPercent)
			    {
				    long num3 = num * 100 / totalLength;
				    if (num2 != num3)
				    {
					    num2 = num3;
                        if (report != null)
                        {
                            report.Invoke(num, totalLength);
                        }
				    }
			    }
			    else
			    {
                    if (report != null)
                    {
                        report.Invoke(num, totalLength);
                    }
			    }
		    }
		    return OperateResult.CreateSuccessResult();
	    }

        //[AsyncStateMachine(typeof(<CreateSocketAndConnectAsync>d__39))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<Socket>> CreateSocketAndConnectAsync(IPEndPoint endPoint, int timeOut, IPEndPoint local = null)
        //{
        //    <CreateSocketAndConnectAsync>d__39 stateMachine = new <CreateSocketAndConnectAsync>d__39();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<Socket>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.endPoint = endPoint;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.local = local;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<CreateSocketAndConnectAsync>d__40))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<Socket>> CreateSocketAndConnectAsync(string ipAddress, int port)
        //{
        //    <CreateSocketAndConnectAsync>d__40 stateMachine = new <CreateSocketAndConnectAsync>d__40();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<Socket>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.ipAddress = ipAddress;
        //    stateMachine.port = port;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<CreateSocketAndConnectAsync>d__41))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<Socket>> CreateSocketAndConnectAsync(string ipAddress, int port, int timeOut)
        //{
        //    <CreateSocketAndConnectAsync>d__41 stateMachine = new <CreateSocketAndConnectAsync>d__41();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<Socket>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.ipAddress = ipAddress;
        //    stateMachine.port = port;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveAsync>d__42))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[]>> ReceiveAsync(Socket socket, int length, int timeOut = 60000, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveAsync>d__42 stateMachine = new <ReceiveAsync>d__42();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.length = length;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveAsync>d__43))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int>> ReceiveAsync(Socket socket, byte[] buffer, int offset, int length, int timeOut = 60000, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveAsync>d__43 stateMachine = new <ReceiveAsync>d__43();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.buffer = buffer;
        //    stateMachine.offset = offset;
        //    stateMachine.length = length;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveCommandLineFromSocketAsync>d__44))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[]>> ReceiveCommandLineFromSocketAsync(Socket socket, byte endCode, int timeout = int.MaxValue)
        //{
        //    <ReceiveCommandLineFromSocketAsync>d__44 stateMachine = new <ReceiveCommandLineFromSocketAsync>d__44();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.endCode = endCode;
        //    stateMachine.timeout = timeout;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveCommandLineFromSocketAsync>d__45))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[]>> ReceiveCommandLineFromSocketAsync(Socket socket, byte endCode1, byte endCode2, int timeout = 60000)
        //{
        //    <ReceiveCommandLineFromSocketAsync>d__45 stateMachine = new <ReceiveCommandLineFromSocketAsync>d__45();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.endCode1 = endCode1;
        //    stateMachine.endCode2 = endCode2;
        //    stateMachine.timeout = timeout;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendAsync>d__46))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendAsync(Socket socket, byte[] data)
        //{
        //    <SendAsync>d__46 stateMachine = new <SendAsync>d__46();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.data = data;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendAsync>d__47))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendAsync(Socket socket, byte[] data, int offset, int size)
        //{
        //    <SendAsync>d__47 stateMachine = new <SendAsync>d__47();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.data = data;
        //    stateMachine.offset = offset;
        //    stateMachine.size = size;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveByMessageAsync>d__48))]
        //[DebuggerStepThrough]
        //protected virtual Task<OperateResult<byte[]>> ReceiveByMessageAsync(Socket socket, int timeOut, INetMessage netMessage, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveByMessageAsync>d__48 stateMachine = new <ReceiveByMessageAsync>d__48();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.netMessage = netMessage;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReadStreamAsync>d__49))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int>> ReadStreamAsync(Stream stream, byte[] buffer)
        //{
        //    <ReadStreamAsync>d__49 stateMachine = new <ReadStreamAsync>d__49();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.stream = stream;
        //    stateMachine.buffer = buffer;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<WriteStreamAsync>d__50))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> WriteStreamAsync(Stream stream, byte[] buffer)
        //{
        //    <WriteStreamAsync>d__50 stateMachine = new <WriteStreamAsync>d__50();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.stream = stream;
        //    stateMachine.buffer = buffer;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveLongAsync>d__51))]
        //[DebuggerStepThrough]
        //private Task<OperateResult<long>> ReceiveLongAsync(Socket socket)
        //{
        //    <ReceiveLongAsync>d__51 stateMachine = new <ReceiveLongAsync>d__51();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<long>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendLongAsync>d__52))]
        //[DebuggerStepThrough]
        //private Task<OperateResult> SendLongAsync(Socket socket, long value)
        //{
        //    <SendLongAsync>d__52 stateMachine = new <SendLongAsync>d__52();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.value = value;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendBaseAndCheckReceiveAsync>d__53))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendBaseAndCheckReceiveAsync(Socket socket, int headCode, int customer, byte[] send)
        //{
        //    <SendBaseAndCheckReceiveAsync>d__53 stateMachine = new <SendBaseAndCheckReceiveAsync>d__53();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.headCode = headCode;
        //    stateMachine.customer = customer;
        //    stateMachine.send = send;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendBytesAndCheckReceiveAsync>d__54))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendBytesAndCheckReceiveAsync(Socket socket, int customer, byte[] send)
        //{
        //    <SendBytesAndCheckReceiveAsync>d__54 stateMachine = new <SendBytesAndCheckReceiveAsync>d__54();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.customer = customer;
        //    stateMachine.send = send;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendStringAndCheckReceiveAsync>d__55))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendStringAndCheckReceiveAsync(Socket socket, int customer, string send)
        //{
        //    <SendStringAndCheckReceiveAsync>d__55 stateMachine = new <SendStringAndCheckReceiveAsync>d__55();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.customer = customer;
        //    stateMachine.send = send;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendStringAndCheckReceiveAsync>d__56))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendStringAndCheckReceiveAsync(Socket socket, int customer, string[] sends)
        //{
        //    <SendStringAndCheckReceiveAsync>d__56 stateMachine = new <SendStringAndCheckReceiveAsync>d__56();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.customer = customer;
        //    stateMachine.sends = sends;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendAccountAndCheckReceiveAsync>d__57))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendAccountAndCheckReceiveAsync(Socket socket, int customer, string name, string pwd)
        //{
        //    <SendAccountAndCheckReceiveAsync>d__57 stateMachine = new <SendAccountAndCheckReceiveAsync>d__57();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.customer = customer;
        //    stateMachine.name = name;
        //    stateMachine.pwd = pwd;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveAndCheckBytesAsync>d__58))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[], byte[]>> ReceiveAndCheckBytesAsync(Socket socket, int timeout)
        //{
        //    <ReceiveAndCheckBytesAsync>d__58 stateMachine = new <ReceiveAndCheckBytesAsync>d__58();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[], byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeout = timeout;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveStringContentFromSocketAsync>d__59))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int, string>> ReceiveStringContentFromSocketAsync(Socket socket, int timeOut = 30000)
        //{
        //    <ReceiveStringContentFromSocketAsync>d__59 stateMachine = new <ReceiveStringContentFromSocketAsync>d__59();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int, string>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveStringArrayContentFromSocketAsync>d__60))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int, string[]>> ReceiveStringArrayContentFromSocketAsync(Socket socket, int timeOut = 30000)
        //{
        //    <ReceiveStringArrayContentFromSocketAsync>d__60 stateMachine = new <ReceiveStringArrayContentFromSocketAsync>d__60();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int, string[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveBytesContentFromSocketAsync>d__61))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int, byte[]>> ReceiveBytesContentFromSocketAsync(Socket socket, int timeout = 30000)
        //{
        //    <ReceiveBytesContentFromSocketAsync>d__61 stateMachine = new <ReceiveBytesContentFromSocketAsync>d__61();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int, byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeout = timeout;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendStreamToSocketAsync>d__62))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendStreamToSocketAsync(Socket socket, Stream stream, long receive, Action<long, long> report, bool reportByPercent)
        //{
        //    <SendStreamToSocketAsync>d__62 stateMachine = new <SendStreamToSocketAsync>d__62();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.stream = stream;
        //    stateMachine.receive = receive;
        //    stateMachine.report = report;
        //    stateMachine.reportByPercent = reportByPercent;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<WriteStreamFromSocketAsync>d__63))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> WriteStreamFromSocketAsync(Socket socket, Stream stream, long totalLength, Action<long, long> report, bool reportByPercent)
        //{
        //    <WriteStreamFromSocketAsync>d__63 stateMachine = new <WriteStreamFromSocketAsync>d__63();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.stream = stream;
        //    stateMachine.totalLength = totalLength;
        //    stateMachine.report = report;
        //    stateMachine.reportByPercent = reportByPercent;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

	    protected OperateResult<WebSocketMessage> ReceiveWebSocketPayload(Socket socket)
	    {
		    List<byte> list = new List<byte>();
		    OperateResult<WebSocketMessage, bool> operateResult;
		    do
		    {
			    operateResult = ReceiveFrameWebSocketPayload(socket);
			    if (!operateResult.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<WebSocketMessage>(operateResult);
			    }
			    list.AddRange(operateResult.Content1.Payload);
		    }
		    while (!operateResult.Content2);
		    return OperateResult.CreateSuccessResult(new WebSocketMessage
		    {
			    HasMask = operateResult.Content1.HasMask,
			    OpCode = operateResult.Content1.OpCode,
			    Payload = list.ToArray()
		    });
	    }

	    protected OperateResult<WebSocketMessage, bool> ReceiveFrameWebSocketPayload(Socket socket)
	    {
		    OperateResult<byte[]> operateResult = Receive(socket, 2, 5000);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<WebSocketMessage, bool>(operateResult);
		    }
		    bool value = (operateResult.Content[0] & 0x80) == 128;
		    bool flag = (operateResult.Content[1] & 0x80) == 128;
		    int opCode = operateResult.Content[0] & 0xF;
		    byte[] array = null;
		    int num = operateResult.Content[1] & 0x7F;
		    switch (num)
		    {
		    case 126:
		    {
			    OperateResult<byte[]> operateResult3 = Receive(socket, 2, 5000);
			    if (!operateResult3.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<WebSocketMessage, bool>(operateResult3);
			    }
			    Array.Reverse(operateResult3.Content);
			    num = BitConverter.ToUInt16(operateResult3.Content, 0);
			    break;
		    }
		    case 127:
		    {
			    OperateResult<byte[]> operateResult2 = Receive(socket, 8, 5000);
			    if (!operateResult2.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<WebSocketMessage, bool>(operateResult2);
			    }
			    Array.Reverse(operateResult2.Content);
			    num = (int)BitConverter.ToUInt64(operateResult2.Content, 0);
			    break;
		    }
		    }
		    if (flag)
		    {
			    OperateResult<byte[]> operateResult4 = Receive(socket, 4, 5000);
			    if (!operateResult4.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<WebSocketMessage, bool>(operateResult4);
			    }
			    array = operateResult4.Content;
		    }
		    OperateResult<byte[]> operateResult5 = Receive(socket, num);
		    if (!operateResult5.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<WebSocketMessage, bool>(operateResult5);
		    }
		    if (flag)
		    {
			    for (int i = 0; i < operateResult5.Content.Length; i++)
			    {
				    operateResult5.Content[i] = (byte)(operateResult5.Content[i] ^ array[i % 4]);
			    }
		    }
		    return OperateResult.CreateSuccessResult(new WebSocketMessage
		    {
			    HasMask = flag,
			    OpCode = opCode,
			    Payload = operateResult5.Content
		    }, value);
	    }

        //[AsyncStateMachine(typeof(<ReceiveWebSocketPayloadAsync>d__66))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<WebSocketMessage>> ReceiveWebSocketPayloadAsync(Socket socket)
        //{
        //    <ReceiveWebSocketPayloadAsync>d__66 stateMachine = new <ReceiveWebSocketPayloadAsync>d__66();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<WebSocketMessage>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveFrameWebSocketPayloadAsync>d__67))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<WebSocketMessage, bool>> ReceiveFrameWebSocketPayloadAsync(Socket socket)
        //{
        //    <ReceiveFrameWebSocketPayloadAsync>d__67 stateMachine = new <ReceiveFrameWebSocketPayloadAsync>d__67();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<WebSocketMessage, bool>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

	    private OperateResult<int> ReceiveMqttRemainingLength(Socket socket)
	    {
		    List<byte> list = new List<byte>();
		    OperateResult<byte[]> operateResult;
		    do
		    {
			    operateResult = Receive(socket, 1, 5000);
			    if (!operateResult.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<int>(operateResult);
			    }
			    list.Add(operateResult.Content[0]);
		    }
		    while (operateResult.Content[0] >= 128 && list.Count < 4);
		    if (list.Count > 4)
		    {
			    return new OperateResult<int>("Receive Length is too long!");
		    }
		    if (list.Count == 1)
		    {
			    return OperateResult.CreateSuccessResult((int)list[0]);
		    }
		    if (list.Count == 2)
		    {
			    return OperateResult.CreateSuccessResult(list[0] - 128 + list[1] * 128);
		    }
		    if (list.Count == 3)
		    {
			    return OperateResult.CreateSuccessResult(list[0] - 128 + (list[1] - 128) * 128 + list[2] * 128 * 128);
		    }
		    return OperateResult.CreateSuccessResult(list[0] - 128 + (list[1] - 128) * 128 + (list[2] - 128) * 128 * 128 + list[3] * 128 * 128 * 128);
	    }

	    protected OperateResult<byte, byte[]> ReceiveMqttMessage(Socket socket, int timeOut, Action<long, long> reportProgress = null)
	    {
		    OperateResult<byte[]> operateResult = Receive(socket, 1, timeOut);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<byte, byte[]>(operateResult);
		    }
		    OperateResult<int> operateResult2 = ReceiveMqttRemainingLength(socket);
		    if (!operateResult2.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<byte, byte[]>(operateResult2);
		    }
		    if (operateResult.Content[0] >> 4 == 15)
		    {
			    reportProgress = null;
		    }
		    if (operateResult.Content[0] >> 4 == 0)
		    {
			    reportProgress = null;
		    }
		    OperateResult<byte[]> operateResult3 = Receive(socket, operateResult2.Content, 60000, reportProgress);
		    if (!operateResult3.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<byte, byte[]>(operateResult3);
		    }
		    return OperateResult.CreateSuccessResult(operateResult.Content[0], operateResult3.Content);
	    }

	    protected OperateResult ReceiveMqttStream(Socket socket, Stream stream, long fileSize, int timeOut, Action<long, long> reportProgress = null)
	    {
		    long num = 0L;
		    while (num < fileSize)
		    {
			    OperateResult<byte, byte[]> operateResult = ReceiveMqttMessage(socket, timeOut);
			    if (!operateResult.IsSuccess)
			    {
				    return operateResult;
			    }
			    if (operateResult.Content1 == 0)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    return new OperateResult(Encoding.UTF8.GetString(operateResult.Content2));
			    }
			    OperateResult operateResult2 = WriteStream(stream, operateResult.Content2);
			    if (!operateResult2.IsSuccess)
			    {
				    return operateResult2;
			    }
			    num += operateResult.Content2.Length;
			    byte[] array = new byte[16];
			    BitConverter.GetBytes(num).CopyTo(array, 0);
			    BitConverter.GetBytes(fileSize).CopyTo(array, 8);
			    OperateResult operateResult3 = Send(socket, MqttHelper.BuildMqttCommand(100, null, array).Content);
			    if (!operateResult3.IsSuccess)
			    {
				    return operateResult3;
			    }
                if (reportProgress != null)
                {
                    reportProgress.Invoke(num, fileSize);
                }
		    }
		    return OperateResult.CreateSuccessResult();
	    }

	    protected OperateResult SendMqttStream(Socket socket, Stream stream, long fileSize, int timeOut, Action<long, long> reportProgress = null)
	    {
		    byte[] array = new byte[fileCacheSize];
		    long num = 0L;
		    stream.Position = 0L;
		    while (num < fileSize)
		    {
			    OperateResult<int> operateResult = ReadStream(stream, array);
			    if (!operateResult.IsSuccess)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    return operateResult;
			    }
			    num += operateResult.Content;
			    OperateResult operateResult2 = Send(socket, MqttHelper.BuildMqttCommand(100, null, array.SelectBegin(operateResult.Content)).Content);
			    if (!operateResult2.IsSuccess)
			    {
                    if (socket != null)
                    {
                        socket.Close();
                    }
				    return operateResult2;
			    }
			    OperateResult<byte, byte[]> operateResult3 = ReceiveMqttMessage(socket, timeOut);
			    if (!operateResult3.IsSuccess)
			    {
				    return operateResult3;
			    }
                if (reportProgress != null)
                {
                    reportProgress.Invoke(num, fileSize);
                }
		    }
		    return OperateResult.CreateSuccessResult();
	    }

	    protected OperateResult SendMqttFile(Socket socket, string filename, string servername, string filetag, Action<long, long> reportProgress = null)
	    {
		    FileInfo fileInfo = new FileInfo(filename);
		    if (!File.Exists(filename))
		    {
			    OperateResult operateResult = Send(socket, MqttHelper.BuildMqttCommand(0, null, Encoding.UTF8.GetBytes(StringResources.Language.FileNotExist)).Content);
			    if (!operateResult.IsSuccess)
			    {
				    return operateResult;
			    }
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult(StringResources.Language.FileNotExist);
		    }
		    string[] data = new string[3]
		    {
			    servername,
			    fileInfo.Length.ToString(),
			    filetag
		    };
		    OperateResult operateResult2 = Send(socket, MqttHelper.BuildMqttCommand(100, null, HslProtocol.PackStringArrayToByte(data)).Content);
		    if (!operateResult2.IsSuccess)
		    {
			    return operateResult2;
		    }
		    OperateResult<byte, byte[]> operateResult3 = ReceiveMqttMessage(socket, 60000);
		    if (!operateResult3.IsSuccess)
		    {
			    return operateResult3;
		    }
		    if (operateResult3.Content1 == 0)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult(Encoding.UTF8.GetString(operateResult3.Content2));
		    }
		    try
		    {
			    OperateResult result = new OperateResult();
			    using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
			    {
				    result = SendMqttStream(socket, stream, fileInfo.Length, 60000, reportProgress);
			    }
			    return result;
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult("SendMqttStream Exception -> " + ex.Message);
		    }
	    }

	    protected OperateResult SendMqttFile(Socket socket, Stream stream, string servername, string filetag, Action<long, long> reportProgress = null)
	    {
		    string[] data = new string[3]
		    {
			    servername,
			    stream.Length.ToString(),
			    filetag
		    };
		    OperateResult operateResult = Send(socket, MqttHelper.BuildMqttCommand(100, null, HslProtocol.PackStringArrayToByte(data)).Content);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult;
		    }
		    OperateResult<byte, byte[]> operateResult2 = ReceiveMqttMessage(socket, 60000);
		    if (!operateResult2.IsSuccess)
		    {
			    return operateResult2;
		    }
		    if (operateResult2.Content1 == 0)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult(Encoding.UTF8.GetString(operateResult2.Content2));
		    }
		    try
		    {
			    return SendMqttStream(socket, stream, stream.Length, 60000, reportProgress);
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult("SendMqttStream Exception -> " + ex.Message);
		    }
	    }

	    protected OperateResult<FileBaseInfo> ReceiveMqttFile(Socket socket, object source, Action<long, long> reportProgress = null)
	    {
		    OperateResult<byte, byte[]> operateResult = ReceiveMqttMessage(socket, 60000);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<FileBaseInfo>(operateResult);
		    }
		    if (operateResult.Content1 == 0)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<FileBaseInfo>(Encoding.UTF8.GetString(operateResult.Content2));
		    }
		    FileBaseInfo fileBaseInfo = new FileBaseInfo();
		    string[] array = HslProtocol.UnPackStringArrayFromByte(operateResult.Content2);
		    fileBaseInfo.Name = array[0];
		    fileBaseInfo.Size = long.Parse(array[1]);
		    fileBaseInfo.Tag = array[2];
		    Send(socket, MqttHelper.BuildMqttCommand(100, null, null).Content);
		    try
		    {
			    OperateResult operateResult2 = null;
			    string text = source as string;
			    if (text != null)
			    {
				    using (FileStream stream = new FileStream(text, FileMode.Create, FileAccess.Write))
				    {
					    operateResult2 = ReceiveMqttStream(socket, stream, fileBaseInfo.Size, 60000, reportProgress);
				    }
				    if (!operateResult2.IsSuccess)
				    {
					    if (File.Exists(text))
					    {
						    File.Delete(text);
					    }
					    return OperateResult.CreateFailedResult<FileBaseInfo>(operateResult2);
				    }
			    }
			    else
			    {
				    Stream stream2 = source as Stream;
				    if (stream2 == null)
				    {
					    throw new Exception("Not Supported Type");
				    }
				    operateResult2 = ReceiveMqttStream(socket, stream2, fileBaseInfo.Size, 60000, reportProgress);
			    }
			    return OperateResult.CreateSuccessResult(fileBaseInfo);
		    }
		    catch (Exception ex)
		    {
                if (socket != null)
                {
                    socket.Close();
                }
			    return new OperateResult<FileBaseInfo>(ex.Message);
		    }
	    }

        //[AsyncStateMachine(typeof(<ReceiveMqttRemainingLengthAsync>d__75))]
        //[DebuggerStepThrough]
        //private Task<OperateResult<int>> ReceiveMqttRemainingLengthAsync(Socket socket)
        //{
        //    <ReceiveMqttRemainingLengthAsync>d__75 stateMachine = new <ReceiveMqttRemainingLengthAsync>d__75();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveMqttMessageAsync>d__76))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte, byte[]>> ReceiveMqttMessageAsync(Socket socket, int timeOut, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveMqttMessageAsync>d__76 stateMachine = new <ReceiveMqttMessageAsync>d__76();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte, byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveMqttStreamAsync>d__77))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> ReceiveMqttStreamAsync(Socket socket, Stream stream, long fileSize, int timeOut, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveMqttStreamAsync>d__77 stateMachine = new <ReceiveMqttStreamAsync>d__77();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.stream = stream;
        //    stateMachine.fileSize = fileSize;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendMqttStreamAsync>d__78))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendMqttStreamAsync(Socket socket, Stream stream, long fileSize, int timeOut, Action<long, long> reportProgress = null)
        //{
        //    <SendMqttStreamAsync>d__78 stateMachine = new <SendMqttStreamAsync>d__78();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.stream = stream;
        //    stateMachine.fileSize = fileSize;
        //    stateMachine.timeOut = timeOut;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendMqttFileAsync>d__79))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendMqttFileAsync(Socket socket, string filename, string servername, string filetag, Action<long, long> reportProgress = null)
        //{
        //    <SendMqttFileAsync>d__79 stateMachine = new <SendMqttFileAsync>d__79();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.filename = filename;
        //    stateMachine.servername = servername;
        //    stateMachine.filetag = filetag;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<SendMqttFileAsync>d__80))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult> SendMqttFileAsync(Socket socket, Stream stream, string servername, string filetag, Action<long, long> reportProgress = null)
        //{
        //    <SendMqttFileAsync>d__80 stateMachine = new <SendMqttFileAsync>d__80();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.stream = stream;
        //    stateMachine.servername = servername;
        //    stateMachine.filetag = filetag;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveMqttFileAsync>d__81))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<FileBaseInfo>> ReceiveMqttFileAsync(Socket socket, object source, Action<long, long> reportProgress = null)
        //{
        //    <ReceiveMqttFileAsync>d__81 stateMachine = new <ReceiveMqttFileAsync>d__81();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<FileBaseInfo>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.source = source;
        //    stateMachine.reportProgress = reportProgress;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

	    protected OperateResult<byte[]> ReceiveRedisCommandString(Socket socket, int length)
	    {
		    List<byte> list = new List<byte>();
		    OperateResult<byte[]> operateResult = Receive(socket, length);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult;
		    }
		    list.AddRange(operateResult.Content);
		    OperateResult<byte[]> operateResult2 = ReceiveCommandLineFromSocket(socket, 10);
		    if (!operateResult2.IsSuccess)
		    {
			    return operateResult2;
		    }
		    list.AddRange(operateResult2.Content);
		    return OperateResult.CreateSuccessResult(list.ToArray());
	    }

	    protected OperateResult<byte[]> ReceiveRedisCommand(Socket socket)
	    {
		    List<byte> list = new List<byte>();
		    OperateResult<byte[]> operateResult = ReceiveCommandLineFromSocket(socket, 10);
		    if (!operateResult.IsSuccess)
		    {
			    return operateResult;
		    }
		    list.AddRange(operateResult.Content);
		    if (operateResult.Content[0] == 43 || operateResult.Content[0] == 45 || operateResult.Content[0] == 58)
		    {
			    return OperateResult.CreateSuccessResult(list.ToArray());
		    }
		    if (operateResult.Content[0] == 36)
		    {
			    OperateResult<int> numberFromCommandLine = RedisHelper.GetNumberFromCommandLine(operateResult.Content);
			    if (!numberFromCommandLine.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<byte[]>(numberFromCommandLine);
			    }
			    if (numberFromCommandLine.Content < 0)
			    {
				    return OperateResult.CreateSuccessResult(list.ToArray());
			    }
			    OperateResult<byte[]> operateResult2 = ReceiveRedisCommandString(socket, numberFromCommandLine.Content);
			    if (!operateResult2.IsSuccess)
			    {
				    return operateResult2;
			    }
			    list.AddRange(operateResult2.Content);
			    return OperateResult.CreateSuccessResult(list.ToArray());
		    }
		    if (operateResult.Content[0] == 42)
		    {
			    OperateResult<int> numberFromCommandLine2 = RedisHelper.GetNumberFromCommandLine(operateResult.Content);
			    if (!numberFromCommandLine2.IsSuccess)
			    {
				    return OperateResult.CreateFailedResult<byte[]>(numberFromCommandLine2);
			    }
			    for (int i = 0; i < numberFromCommandLine2.Content; i++)
			    {
				    OperateResult<byte[]> operateResult3 = ReceiveRedisCommand(socket);
				    if (!operateResult3.IsSuccess)
				    {
					    return operateResult3;
				    }
				    list.AddRange(operateResult3.Content);
			    }
			    return OperateResult.CreateSuccessResult(list.ToArray());
		    }
		    return new OperateResult<byte[]>("Not Supported HeadCode: " + operateResult.Content[0].ToString());
	    }

        //[AsyncStateMachine(typeof(<ReceiveRedisCommandStringAsync>d__84))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[]>> ReceiveRedisCommandStringAsync(Socket socket, int length)
        //{
        //    <ReceiveRedisCommandStringAsync>d__84 stateMachine = new <ReceiveRedisCommandStringAsync>d__84();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.length = length;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<ReceiveRedisCommandAsync>d__85))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<byte[]>> ReceiveRedisCommandAsync(Socket socket)
        //{
        //    <ReceiveRedisCommandAsync>d__85 stateMachine = new <ReceiveRedisCommandAsync>d__85();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

	    protected OperateResult<int, int, byte[]> ReceiveHslMessage(Socket socket)
	    {
		    OperateResult<byte[]> operateResult = Receive(socket, 32, 10000);
		    if (!operateResult.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<int, int, byte[]>(operateResult);
		    }
		    int length = BitConverter.ToInt32(operateResult.Content, operateResult.Content.Length - 4);
		    OperateResult<byte[]> operateResult2 = Receive(socket, length);
		    if (!operateResult2.IsSuccess)
		    {
			    return OperateResult.CreateFailedResult<int, int, byte[]>(operateResult2);
		    }
		    byte[] value = HslProtocol.CommandAnalysis(operateResult.Content, operateResult2.Content);
		    int value2 = BitConverter.ToInt32(operateResult.Content, 0);
		    int value3 = BitConverter.ToInt32(operateResult.Content, 4);
		    return OperateResult.CreateSuccessResult(value2, value3, value);
	    }

        //[AsyncStateMachine(typeof(<ReceiveHslMessageAsync>d__87))]
        //[DebuggerStepThrough]
        //protected Task<OperateResult<int, int, byte[]>> ReceiveHslMessageAsync(Socket socket)
        //{
        //    <ReceiveHslMessageAsync>d__87 stateMachine = new <ReceiveHslMessageAsync>d__87();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<int, int, byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.socket = socket;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

	    protected bool DeleteFileByName(string filename)
	    {
		    try
		    {
			    if (!File.Exists(filename))
			    {
				    return true;
			    }
			    File.Delete(filename);
			    return true;
		    }
		    catch (Exception ex)
		    {
                if (LogNet != null)
                {
                    LogNet.WriteException(ToString(), "delete file failed:" + filename, ex);
                }
			    return false;
		    }
	    }

	    protected string PreprocessFolderName(string folder)
	    {
		    if (folder.EndsWith("\\") || folder.EndsWith("/"))
		    {
			    return folder.Substring(0, folder.Length - 1);
		    }
		    return folder;
	    }

	    public override string ToString()
	    {
		    return "NetworkBase";
	    }

	    public static string GetIpAddressHostName(string hostName)
	    {
		    IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
		    IPAddress iPAddress = hostEntry.AddressList[0];
		    return iPAddress.ToString();
	    }
    }
}
